const tryCatch = require('../../utils/tryCatch');
const {
  ServerGetMessageList,
  ServerReadMessage,
  ServerGetFriendsMessage,
  ServerSendMessageToFriend,
  ServerRecallMessage
} = require("../../server/message/index")
const {
  ServerGetGroupMessageList,
  ServerGetGroupMessage,
  ServerSendMessageToGroup,
} = require("../../server/group")
const { ServerGetUserSockIdByID } = require("../../server/user/index")
const socket = require("../socket/initSocket")
const Message = {
  GetMessageList: tryCatch(async (req, res) => {
    const userId = req.query.userId;
    if (userId) {
      const [GetMessageListres, GetGroupMessageListres] = await Promise.all([ServerGetMessageList(userId), ServerGetGroupMessageList(userId)])
      if (GetMessageListres.isok && GetGroupMessageListres.isok) {
        const messageListdata = [...GetMessageListres.data, ...GetGroupMessageListres.data].sort((a, b) => {
          return new Date(b.lastMessageTime).getTime() - new Date(a.lastMessageTime).getTime()
        })
        res.send({
          statusCode: 200,
          data: messageListdata
        })
      } else {
        res.send({
          statusCode: 403,
          errorInfo: "查询失败",
          data: false
        })
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  SearchMessageList: tryCatch(async (req, res) => {
    const userId = req.body.userId;
    const keyword = req.body.keyword;
    if (userId) {
      const [GetMessageListres, GetGroupMessageListres] = await Promise.all([ServerGetMessageList(userId), ServerGetGroupMessageList(userId)])
      if (GetMessageListres.isok && GetGroupMessageListres.isok) {
        const messageListdata = [...GetMessageListres.data, ...GetGroupMessageListres.data].sort((a, b) => {
          return new Date(b.lastMessageTime).getTime() - new Date(a.lastMessageTime).getTime()
        })
        const messagelist = messageListdata.filter((item) => {
          return item.name.indexOf(keyword) !== -1
        })
        res.send({
          statusCode: 200,
          data: messagelist
        })
      } else {
        res.send({
          statusCode: 403,
          errorInfo: "搜索失败",
          data: false
        })
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  MessageRead: tryCatch(async (req, res) => {
    if (req.body.messageId && req.body.type && req.body.userId) {
      const ReadMessageres = await ServerReadMessage({ messageId: req.body.messageId, type: req.body.type, userId: req.body.userId });
      if (ReadMessageres.isok) {
        res.send({
          statusCode: 200,
          data: true
        })
      } else {
        res.send({
          statusCode: 403,
          errorInfo: "失败",
          data: false
        })
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  getHistoryMessages: tryCatch(async (req, res) => {
    const messageId = req.body.messageId
    const messageSize = req.body.messageSize
    const type = req.body.type
    const startId = req.body.startId
    const userId = req.body.userId
    if (messageId && messageSize && type) {
      if (type == 'group') {
        const GroupMessage = await ServerGetGroupMessage({ messageId, pageSize: messageSize, startId })
        if (GroupMessage.isok) {
          res.send({
            statusCode: 200,
            data: GroupMessage.data
          })
        } else {
          res.send({
            data: false,
            statusCode: 403,
            errorInfo: GroupMessage.message,
          })
        }
      } else {
        const GroupMessage = await ServerGetFriendsMessage({ messageId, pageSize: messageSize, startId, userId })
        if (GroupMessage.isok) {
          res.send({
            statusCode: 200,
            data: GroupMessage.data
          })
        } else {
          res.send({
            data: false,
            statusCode: 403,
            errorInfo: GroupMessage.message,
          })
        }
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  SendMessage: tryCatch(async (req, res) => {
    const { id, userId, content, type, messageType, messageSendType } = req.body;
    if (userId && content && type) {
      if (type == "friend") {
        const sendfriendres = await ServerSendMessageToFriend({
          friendId: id,
          userId,
          content,
          messageType: messageType || "data",
          messageSendType: messageSendType !== undefined ? messageSendType : 1
        });
        if (sendfriendres.isok) {
          ServerGetUserSockIdByID(sendfriendres.data.friendId).then((socketres) => {
            if (socketres.isok) {
              const friendsocketId = socketres.data.socketid;
              if (friendsocketId) {
                socket.io.to(friendsocketId).emit("friendmessage", sendfriendres.data)
                socket.io.to(friendsocketId).emit("messagelist", {
                  messageId: sendfriendres.data.messageId,
                  type: "friend",
                  message: content,
                  messageType: messageType || "data",
                  noMessageNum: sendfriendres.updatauserFriendMid.friendUserId1 == sendfriendres.data.friendId ? sendfriendres.updatauserFriendMid.noMessageNum1 : sendfriendres.updatauserFriendMid.noMessageNum2,
                  lastMessageTime: sendfriendres.lastMessageTime
                })
              }
            }
          })
          ServerGetUserSockIdByID(userId).then((socketres) => {
            if (socketres.isok) {
              const friendsocketId = socketres.data.socketid;
              if (friendsocketId) {
                socket.io.to(friendsocketId).emit("friendmessage", sendfriendres.data)
                socket.io.to(friendsocketId).emit("messagelist", {
                  messageId: sendfriendres.data.messageId,
                  type: "friend",
                  message: content,
                  messageType: messageType || "data",
                  noMessageNum: sendfriendres.updatauserFriendMid.friendUserId1 == userId ? sendfriendres.updatauserFriendMid.noMessageNum1 : sendfriendres.updatauserFriendMid.noMessageNum2,
                  lastMessageTime: sendfriendres.lastMessageTime
                })
              }
            }
          })
          res.send({
            statusCode: 200,
            data: true
          })
        } else {
          res.send({
            data: false,
            statusCode: 403,
            errorInfo: "发送失败",
          })
        }
      } else {
        const sendgroup = await ServerSendMessageToGroup({
          groupId: id,
          userId,
          content,
          messageType: messageType || "data",
          messageSendType: messageSendType !== undefined ? messageSendType : 1
        });
        if (sendgroup.isok) {
          socket.io.to(sendgroup.group.groupRoom).emit("groupMessage", sendgroup.data)
          socket.io.to(sendgroup.group.groupRoom).emit("messagelist", {
            messageId: sendgroup.data.messageId,
            type: "group",
            message: content,
            messageType: messageType || "data",
            lastMessageTime: sendgroup.data.createdAt
          })
          res.send({
            statusCode: 200,
            data: true
          })
        } else {
          res.send({
            data: false,
            statusCode: 403,
            errorInfo: "发送失败",
          })
        }
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  RecallMessage: tryCatch(async (req, res) => {
    const { messageId, type, userId } = req.body;

    if (!messageId || !type || !userId) {
      return res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      });
    }

    const recallResult = await ServerRecallMessage({ messageId, type, userId });

    if (recallResult.isok) {
      // 撤回成功，通过socket通知相关用户
      if (type === "friend") {
        // 通知好友
        const friendUserId = recallResult.data.friendUserId;
        const friendSocketResult = await ServerGetUserSockIdByID(friendUserId);

        if (friendSocketResult.isok && friendSocketResult.data.socketid) {
          // 发送recall_message事件
          socket.io.to(friendSocketResult.data.socketid).emit("recall_message", {
            messageId: recallResult.data.messageId,
            type: "friend",
          });
        }

        // 通知自己
        const userSocketResult = await ServerGetUserSockIdByID(userId);

        if (userSocketResult.isok && userSocketResult.data.socketid) {
          // 发送recall_message事件
          socket.io.to(userSocketResult.data.socketid).emit("recall_message", {
            messageId: recallResult.data.messageId,
            type: "friend",
          });
        }
      } else if (type === "group") {
        // 群聊消息撤回，通知群组所有成员
        // 发送recall_message事件
        socket.io.to(recallResult.data.group.groupRoom).emit("recall_message", {
          messageId: recallResult.data.messageId,
          type: "group"
        });
      }

      return res.send({
        statusCode: 200,
        data: true
      });
    } else {
      return res.send({
        statusCode: 403,
        errorInfo: recallResult.message,
        data: false
      });
    }
  })
}

module.exports = Message;